<?php
/**
 * 
 * +------------------------------------------------------------+
 * @category MysqlDb 
 * +------------------------------------------------------------+
 * Mysql数据库驱动类，支持同时连接多个数据库
 * +------------------------------------------------------------+
 *
 * @author anzai <236049524@qq.com>
 * @copyright http://www.judianyun.com 2012
 * @version 1.0
 *
 * Modified at : 2012-02-16 10:03:13
 *
 */
class MysqlDb extends Db {
	//关闭数据库
	public function close(){
		mysql_ping($this->_links[$this->_linkID]);
		$this->_links[$this->_linkID] && mysql_close($this->_links[$this->_linkID]);
	}
	
	//连接数据库
	public function connect($config='',$linkId=0){
		$this->_linkID = $linkId;
		try {
			if (!isset($this->_links[$linkId])){
				$config = empty($config) ? $this->_config[$linkId] : $config;
				$this->_links[$linkId] = true==$config['pconnect'] ? mysql_pconnect($config['dbhost'].':'.$config['dbport'], $config['dbuser'], $config['dbpass'],1) : mysql_connect($config['dbhost'].':'.$config['dbport'], $config['dbuser'], $config['dbpass'],1);

				if($this->_links[$linkId]){
					$this->version = mysql_get_server_info();
					if($this->version > '4.1'){
						$dbcharset = $config['dbcharset'];
						$charset   = $config['charset'];
						$dbcharset = !$dbcharset && in_array(strtolower($charset), array('gbk', 'big5', 'utf-8')) ? str_replace('-', '', $charset) : $dbcharset;
						$serverset = $dbcharset ? 'character_set_connection='.$dbcharset.', character_set_results='.$dbcharset.', character_set_client=binary' : '';
						$serverset .= $this->version > '5.0.1' ? ((empty($serverset) ? '' : ',').'sql_mode=\'\'') : '';
						$serverset && $this->exec('SET '.$serverset, $this->_links[$linkId]);
					}
					if(!mysql_select_db($config['dbname'], $this->_links[$linkId])){
						throw new E(sprintf(Helper::L('CLS_MYSQLDB_CONNECT_SELDB'),$config['dbhost'],$config['dbname']).' : '.$this->_error(),'db');
					}
				}else{
					throw new E(Helper::L('CLS_MYSQLDB_CONNECT_LINK').' : '.$this->_error(),'db');
				}
			}
		}catch (E $e){
			$e->getMsg();
		}
		
		return $this;
	}
	
	//统计数据条数
	public function count($sql=''){
 		$sql = empty($sql) ? 'SELECT COUNT(1) FROM '.$this->_table : $sql;
 		$result = $this->query($sql, 'count');
 		$count = mysql_result($result,0);
 		$this->free();
    	return $count;
    }
    
    //获取受影响的行数
	public function affectRow(){
    	return mysql_affected_rows($this->getLink());
    }
    
    //执行SQL语句
	public function exec($sql, $method = ''){
		try{
			parent::exec($sql, $method);
	    	$queryID = mysql_query($sql,$this->getLink());
	    	if (!$queryID) {
	    		throw new E(Helper::L('CLS_MYSQLDB_EXEC_SQL').' : '.H($sql),EXCEPTION_T_DB, 5, $method, $this->reflection);
	    	}
	    	$this->_recordQuery($sql);
    	}catch(E $e){
        	$e->getMsg();
        }
        
    	return $queryID;
	}
	
	//获取所有数据行
	public function getAll($sql,$result_type=MYSQL_ASSOC){
		$result = $this->query($sql, 'getAll');
		$data = array();
		while ($row = $this->_fetch_array($result,$result_type)) {
    		$data[] = $row;
    	}
    	$this->free();
    	return $data;
	}
	
	//获取表字段信息
	public function getFields($tablename=''){
		empty($tablename) && $tablename = $this->_table;
    	$datas = $this->getALL('DESCRIBE '.$tablename);
    	if (empty($datas)) return array();
    	foreach ($datas as $field){
    		$fields[$field['Field']] = array(
    			'value' => $field['Default'],   //默认值
				'updated' => false,   //是否有更新
    			'type' => $field['Type'], //字段类型
    			'key' => $field['Key']=='PRI' ? 1 : 0, //是否主键
    		);
    	}
    	return $fields;
	}
	
	//获取单调数据
	public function getOne($sql,$result_type=MYSQL_ASSOC){
		return parent::getOne($sql,$result_type);
	}
	
	//释放资源
	protected function free(){
		$res = true;
		if($this->_queryID){
			$res = mysql_free_result($this->_queryID);
        	$this->_queryID = null;
		}
		return $res;
	}
	
	//获取最后一次插入数据库表的ID
	public function lastInsertId(){
		if (!$this->_links[$this->_linkID]) 
			return 0;
		return mysql_insert_id($this->_links[$this->_linkID]);
	}
	
	public function num_rows($res){
		$nums = mysql_num_rows($res);
		$this->free();
		return $nums;
	}
	
	private function _error() {
		return (($this->_links[$this->_linkID]) ? mysql_error($this->_links[$this->_linkID]) : mysql_error());
	}
    
	protected function _fetch_array($result,$result_type=MYSQL_ASSOC){
    	return mysql_fetch_array($result,$result_type);
    }
}

?>